const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const helper = require('./routes/helpers');//注册hbs帮助方法
const $ = require('jquery');

//导入中间件
const {initLocals} = require('./routes/middleware');//全局

//导入相关模块
const indexRouter = require('./routes/index');//主页
const usersRouter = require('./routes/page/users');//个人中心
const channelRouter = require('./routes/channel/index');//频道
const liveRouter = require('./routes/page/live');//直播
const adminRouter = require('./routes/page/admin');//管理


const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');


//应用中间件    线性↓
app.use(logger('dev'));//日志
app.use(express.json());//获取ajax传递json
app.use(express.urlencoded({extended: false}));//解析url参数
app.use(cookieParser());//cookie解析

//设置静态目录
app.use(express.static(path.join(__dirname, 'src')));

//自定义中间件  -->要写在路由前面
app.use(initLocals);


//路由注册
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/channel', channelRouter);//导出xx的路由模块
app.use('/live', liveRouter);
app.use('/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
